package jsu.hx.lost.Service;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import jsu.hx.lost.Config.JwtUtil;
import jsu.hx.lost.Mapper.StatMapper;
import jsu.hx.lost.Mapper.UserMapper;
import jsu.hx.lost.Model.dto.FindItemDTO;
import jsu.hx.lost.Model.dto.UserExportDTO;
import jsu.hx.lost.Model.dto.UserImportDTO;
import jsu.hx.lost.Model.entity.LoginLog;
import jsu.hx.lost.Model.vo.PageResult;
import jsu.hx.lost.Model.entity.User;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;  // MyBatis-Plus 自动注入 mapper

    @Autowired
    private JwtUtil jwtUtil;  // 注入 JwtUtil 工具类，用来生成 Token
    @Autowired
    private AliyunOssService aliyunOssService; // 替换 FileStorageService
    @Autowired
    private StatMapper statMapper;
    /**
     * 根据手机号获取用户 ID
     * @param phone 手机号
     * @return 用户 ID
     */
    public Long getUserIdByPhone(String phone) {
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("phone", phone));
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        return user.getId();
    }
    // UserService.java 中新增方法
    public User getUserByPhone(String phone) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", phone).eq("is_deleted", 0);
        return userMapper.selectOne(queryWrapper);
    }
    /**
     * 通过用户名或邮箱验证用户身份并生成 JWT Token
     * @param phone 用户名或邮箱
     * @param password 用户密码
     * @return 生成的 JWT Token
     */
    public Map<String, Object> authenticateUser(String phone, String password) {
        User user = userMapper.selectOne(new QueryWrapper<User>()
                .eq("phone", phone));

        if (user == null || !password.equals(user.getPassword())) {
            throw new RuntimeException("手机号或密码错误");
        }

        String token = jwtUtil.generateToken(user.getId(), user.getPhone(), user.getRole());

        LoginLog loginLog = new LoginLog();
        loginLog.setUserId(user.getId());
        loginLog.setLoginTime(new Date());  // 使用当前时间
        statMapper.insertLoginLog(loginLog);
        return Map.of(
                "token", token,
                "role", user.getRole(),
                "userId", user.getId(),
                "username",user.getUsername()
        );
    }


    public List<User> getAllUsers() {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_deleted", 0);
        return userMapper.selectList(queryWrapper);
    }

    public ResponseEntity<?> adminRegister(String password, String phone, String fullName, String adminToken) {
        try {
            // 校验管理员令牌
            if (!"ADMIN_SECRET_KEY".equals(adminToken)) {
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body("管理员令牌无效");
            }

            // 检查手机号是否已存在
            if (userMapper.exists(new QueryWrapper<User>().eq("phone", phone))) {
                return ResponseEntity.badRequest().body("手机号已注册");
            }

            // 自动生成用户名和默认头像
            String username = "admin_" + phone;
            String avatarPath = "uploads/avatars/img.png";

            // 创建管理员用户对象
            User adminUser = new User();
            adminUser.setUsername(username);
            adminUser.setPassword(password);
            adminUser.setPhone(phone);
            adminUser.setFullName(fullName);
            adminUser.setProfileImage(avatarPath);
            adminUser.setAddTime(new Date());
            adminUser.setRole(User.Role.ADMIN); // 直接设置为管理员角色
            adminUser.setIsDeleted(0);

            // 插入数据库
            int result = userMapper.insert(adminUser);
            if (result > 0) {
                return ResponseEntity.status(HttpStatus.CREATED).body("管理员注册成功");
            } else {
                return ResponseEntity.internalServerError().body("管理员用户创建失败");
            }
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body("系统错误: " + e.getMessage());
        }
    }
    public ResponseEntity<?> register(String password, String phone, String fullName) {
        try {
            // 检查手机号是否已存在
            if (userMapper.exists(new QueryWrapper<User>().eq("phone", phone))) {
                throw new IllegalArgumentException("手机号已注册");
            }

            // 自动生成用户名（示例：user_手机号）
            String username = "user_" + phone;

            // 设置默认头像路径
            String avatarPath = "uploads/avatars/img.png";

            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            user.setPhone(phone);
            user.setFullName(fullName);
            user.setProfileImage(avatarPath);
            user.setAddTime(new Date());
            user.setRole(User.Role.USER);
            user.setIsDeleted(0);

            int result = userMapper.insert(user);
            if (result > 0) {
                return ResponseEntity.status(HttpStatus.CREATED).body("注册成功");
            } else {
                return ResponseEntity.internalServerError().body("用户创建失败");
            }
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body("系统错误: " + e.getMessage());
        }
    }


    public User getUserById(Long id) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id).eq("is_deleted", 0);
        return userMapper.selectOne(queryWrapper);
    }

    public ResponseEntity<?> updateUser(Long id,
                                        MultipartFile avatarFile,
                                        String username,
                                        String password,
                                        String fullName,
                                        String gender,
                                        String phone) {
        User existingUser = null;
        String oldAvatarPath = null;
        String newAvatarPath = null;

        try {
            System.out.println("接收参数：" + username + "," + phone);
            // 获取现有用户信息
            existingUser = userMapper.selectById(id);
            if (existingUser == null || existingUser.getIsDeleted() == 1) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(
                        Collections.singletonMap("error", "用户不存在")
                );
            }
            oldAvatarPath = existingUser.getProfileImage();

            // 文件上传逻辑（使用阿里云 OSS）
            if (avatarFile != null && !avatarFile.isEmpty()) {
                // 上传新头像到OSS的avatars目录
                newAvatarPath = aliyunOssService.uploadFile(avatarFile, "avatars");
            }

            // 构建更新条件
            UpdateWrapper<User> wrapper = new UpdateWrapper<User>().eq("id", id);

            // 用户名更新逻辑
            if (username != null && !username.isEmpty()) {
                if (!username.equals(existingUser.getUsername())) {
                    if (userMapper.exists(new QueryWrapper<User>()
                            .eq("username", username)
                            .ne("id", id))) {
                        throw new IllegalArgumentException("用户名已被占用");
                    }
                    wrapper.set("username", username);
                }
            }

            // 手机号更新逻辑
            if (phone != null && !phone.isEmpty()) {
                if (!phone.equals(existingUser.getPhone())) {
                    if (userMapper.exists(new QueryWrapper<User>()
                            .eq("phone", phone)
                            .ne("id", id))) {
                        throw new IllegalArgumentException("手机号已被注册");
                    }
                    wrapper.set("phone", phone);
                }
            }

            // 密码更新
            if (password != null && !password.isEmpty()) {
                wrapper.set("password", password);
            }

            // 姓名更新
            if (fullName != null && !fullName.isEmpty()) {
                wrapper.set("full_name", fullName);
            }

            // 性别更新
            if (gender != null) {
                wrapper.set("gender", gender.isEmpty() ? existingUser.getGender() : gender);
            }

            // 更新头像路径
            if (newAvatarPath != null) {
                wrapper.set("profile_image", newAvatarPath);
            }

            // 执行数据库更新
            int result = userMapper.update(null, wrapper);
            if (result <= 0) {
                // 数据库更新失败时删除已上传的新头像
                if (newAvatarPath != null) {
                    aliyunOssService.deleteFile(newAvatarPath);
                }
                return ResponseEntity.status(HttpStatus.CONFLICT).body(
                        Collections.singletonMap("error", "更新操作未生效")
                );
            }

            // 删除旧头像（排除默认头像）
            if (newAvatarPath != null &&
                    oldAvatarPath != null &&
                    !oldAvatarPath.startsWith("http://lost-xin.oss-cn-beijing.aliyuncs.com/avatars/default")) {
                try {
                    aliyunOssService.deleteFile(oldAvatarPath);
                } catch (Exception e) {
                    // 记录删除失败日志，但不影响主流程
                    System.err.println("旧头像删除失败: " + e.getMessage());
                }
            }

            // 返回更新后的用户数据
            User updatedUser = userMapper.selectById(id);
            return ResponseEntity.ok(Map.of(
                    "data", updatedUser,
                    "profileImage", aliyunOssService.getBaseUrl() + updatedUser.getProfileImage()
            ));

        } catch (IllegalArgumentException e) {
            // 业务校验异常处理
            if (newAvatarPath != null) {
                aliyunOssService.deleteFile(newAvatarPath);
            }
            return ResponseEntity.badRequest().body(
                    Collections.singletonMap("error", e.getMessage())
            );
        } catch (IOException e) {
            // 文件流读取异常处理
            if (newAvatarPath != null) {
                aliyunOssService.deleteFile(newAvatarPath);
            }
            return ResponseEntity.internalServerError().body(
                    Collections.singletonMap("error", "文件处理失败: " + e.getMessage())
            );
        } catch (Exception e) {
            // 其他异常处理
            e.printStackTrace();
            if (newAvatarPath != null) {
                aliyunOssService.deleteFile(newAvatarPath);
            }
            return ResponseEntity.internalServerError().body(
                    Collections.singletonMap("error", "系统错误: " + e.getMessage())
            );
        }
    }

    public String deleteUser(Long id) {
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id).set("is_deleted", 1);
        boolean success = userMapper.update(null, updateWrapper) > 0;
        return success ? "User deleted successfully" : "Failed to delete user";
    }

    // UserService.java
    public PageResult<User> getUsersByPage(int page, int pageSize, String username, String sortField, String sortOrder) {
        // 计算偏移量
        int offset = (page - 1) * pageSize;

        // 构建查询条件
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_deleted", 0);

        // 添加模糊搜索条件
        if (StringUtils.hasText(username)) {
            queryWrapper.like("username", username);
        }

        // 添加排序逻辑
        if (StringUtils.hasText(sortField)) {
            String order = "asc".equalsIgnoreCase(sortOrder) ? "ASC" : "DESC";
            queryWrapper.orderBy(true, "asc".equalsIgnoreCase(order), sortField);
        } else {
            queryWrapper.orderByAsc("id"); // 默认按 ID 升序
        }

        // 分页查询
        List<User> userList = userMapper.selectUserList(
                offset,
                pageSize,
                queryWrapper
        );

        // 查询总记录数
        long total = userMapper.selectUserCount(queryWrapper);

        return new PageResult<>(userList, total, page, pageSize);
    }
    // 添加根据条件查询用户的方法（不分页）
    public List<User> getUsersByCondition(String username, String sortField, String sortOrder) {
        // 构建查询条件
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_deleted", 0);

        // 添加模糊搜索条件
        if (StringUtils.hasText(username)) {
            queryWrapper.like("username", username);
        }

        // 添加排序逻辑
        if (StringUtils.hasText(sortField)) {
            String order = "asc".equalsIgnoreCase(sortOrder) ? "ASC" : "DESC";
            queryWrapper.orderBy(true, "asc".equalsIgnoreCase(order), sortField);
        } else {
            queryWrapper.orderByAsc("id"); // 默认按 ID 升序
        }

        // 查询所有符合条件的用户
        return userMapper.selectList(queryWrapper);
    }

    // 修改导出方法，使用传入的用户列表
    public ByteArrayOutputStream exportToExcel(List<User> users) throws Exception {
        // 将User列表转换为UserExportDTO列表
        List<UserExportDTO> exportList = new ArrayList<>();
        for (User user : users) {
            UserExportDTO dto = new UserExportDTO();
            dto.setId(user.getId());
            dto.setUsername(user.getUsername());
            dto.setFullName(user.getFullName());
            dto.setGender(user.getGender());
            dto.setPhone(user.getPhone());
            dto.setRole(user.getRole() != null ? user.getRole().name() : "");
            dto.setAddTime(user.getAddTime());
            dto.setProfileImage(user.getProfileImage());
            exportList.add(dto);
        }

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        EasyExcel.write(outputStream, UserExportDTO.class)
                .sheet("用户数据")
                .doWrite(exportList);
        return outputStream;
    }
    // 添加导入方法
    public Map<String, Object> importFromExcel(MultipartFile file) {
        Map<String, Object> response = new HashMap<>();
        int successCount = 0;
        int failCount = 0;
        List<String> failMessages = new ArrayList<>();

        try (InputStream is = file.getInputStream()) {
            // 使用EasyExcel读取Excel
            List<UserImportDTO> importList = EasyExcel.read(is)
                    .head(UserImportDTO.class)
                    .sheet()
                    .doReadSync();

            for (UserImportDTO dto : importList) {
                try {
                    // 检查手机号是否已存在
                    if (userMapper.exists(new QueryWrapper<User>().eq("phone", dto.getPhone()))) {
                        throw new RuntimeException("手机号已存在: " + dto.getPhone());
                    }

                    // 创建用户对象
                    User user = new User();
                    user.setUsername(dto.getUsername());
                    user.setPassword(dto.getPassword()); // 注意：实际应用中应加密
                    user.setFullName(dto.getFullName());
                    user.setGender(dto.getGender());
                    user.setPhone(dto.getPhone());

                    // 处理角色
                    if ("ADMIN".equalsIgnoreCase(dto.getRole())) {
                        user.setRole(User.Role.ADMIN);
                    } else {
                        user.setRole(User.Role.USER);
                    }

                    user.setProfileImage(dto.getProfileImage() != null ?
                            dto.getProfileImage() : "uploads/avatars/img.png");
                    user.setAddTime(new Date());
                    user.setIsDeleted(0);

                    // 插入数据库
                    userMapper.insert(user);
                    successCount++;
                } catch (Exception e) {
                    failCount++;
                    failMessages.add("行" + (importList.indexOf(dto) + 1) + ": " + e.getMessage());
                }
            }

            response.put("status", "success");
            response.put("message", "导入完成。成功：" + successCount + "条，失败：" + failCount + "条");
            if (!failMessages.isEmpty()) {
                response.put("failDetails", failMessages);
            }
        } catch (Exception e) {
            response.put("status", "error");
            response.put("message", "导入失败: " + e.getMessage());
        }
        return response;
    }
    // 根据查询条件获取用户列表
}
